//
//  FRQAddNFTsViewController.m
//  FRQBluetoothKit_Example
//
//  Created by admin on 2023/10/25.
//  Copyright © 2023 xuchunhai. All rights reserved.
//

#import "FRQAddNFTsViewController.h"
#define KCellID @"MonthCardPayViewsID"
#define KHedderID @"MonthCardPayViewsHedderID"
#define KFooterID @"MonthCardPayViewsFooterID"
#import "FRQAddNFTsSuccessViewController.h"
@interface FRQAddNFTsViewController ()
<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UITextFieldDelegate>
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) NSString *address;
@property (nonatomic,strong) NSString *teamId;
@property (nonatomic,strong) NSMutableArray *arrTeamIds;
@property (nonatomic,strong) NSMutableArray *arrTeamId;
@property (nonatomic,strong) UITextField *txtAddress;
@property (nonatomic,assign) Boolean isVerify;
@end

@implementation FRQAddNFTsViewController

-(UICollectionView *)collectionView{
    if (nil==_collectionView) {
        
        //1.初始化layout
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        //设置collectionView滚动方向
        [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
        //设置headerView的尺寸大小
        layout.headerReferenceSize = CGSizeMake(skScreenWidth, 400);
        //设置尾部的尺寸大小
//        layout.footerReferenceSize = CGSizeMake(self.frame.size.width, 30);
        //        该方法也可以设置itemSize
        
        
        layout.itemSize =CGSizeMake((skScreenWidth-100)/2, 42);
        _collectionView=[[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
        
        [self.view addSubview:_collectionView];
        [_collectionView setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
        
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.mas_topLayoutGuide).offset(0);
            make.left.mas_equalTo(45);
            make.right.mas_equalTo(-45);
            make.bottom.mas_equalTo(self.mas_bottomLayoutGuide).offset(-80);
        }];
        //3.注册collectionViewCell
        //注意，此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致 均为 cellId
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:KCellID];
        //注册headerView  此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致  均为reusableView
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:KHedderID];
        
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:KFooterID];
//        _collectionView.bounces = NO;
        //4.设置代理
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
    }
    return _collectionView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"Add NFTs";
    [self.collectionView reloadData];
    
    self.arrTeamId=[[NSMutableArray alloc] init];
    self.arrTeamIds=[[NSMutableArray alloc] init];
    for (int i=0; i<20; ++i) {
        NSDictionary *dic=@{@"title":@"",@"isTid":@YES};
        [self.arrTeamId addObject:dic];
    }
    
    
    self.collectionView.backgroundColor=skUIColorFromRGB(0x1c1f2a);
    // Do any additional setup after loading the view.
    UIButton *btn=[[UIButton alloc] initWithFrame:CGRectMake(0, skScreenHeight-80, skScreenWidth-90, 42)];
    [self.view addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.mas_bottomLayoutGuideTop).offset(-30);
        make.size.mas_equalTo(CGSizeMake(200, 42));
        make.centerX.mas_equalTo(self.view.mas_centerX);
    }];
    btn.backgroundColor=skphUIColorFromRGB(0x44cd2c,0.8);
    [btn setTitle:@"Upload" forState:(UIControlStateNormal)];
    
    [btn skSetBoardRadius:5 Width:0 andBorderColor:[UIColor clearColor]];
    @weakify(self)
    [[btn
      rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        [self appSysUserNftAdd];
        
    }];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(void)appSysUserNftAdd{
    self.arrTeamIds=[[NSMutableArray alloc] init];
    for (int i =0; i<self.arrTeamId.count; ++i) {
        NSDictionary *dic=[self.arrTeamId objectAtIndex:i];
        NSString *title=[dic objectForKey:@"title"];
        if(title.length>0){
            [self.arrTeamIds addObject:title];
        }
    }
    if(self.arrTeamIds.count==0){
        [SkToast SkToastShow:@"empty"];
        return;
    }
    NSDictionary *dic=@{@"contractAddress":[NSString stringWithFormat:@"%@",self.address],
                        @"tokenIdList":self.arrTeamIds
    };
    
    SHOW_SVP(@"wait");
    [skNetTools skPOSTWithURL:[NSString stringWithFormat:@"%@%@",skURL,@"app/sys/user/nft/add"] parameters:dic cachePolicy:0 callback:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        DISMISS_SVP(0.01);
        NSLog(@"数据=%@",responseObject);
        skNetModel *model=[skNetModel mj_objectWithKeyValues:responseObject];
        if(model.code==200){
            FRQAddNFTsSuccessViewController *view=[[FRQAddNFTsSuccessViewController alloc] init];
            [self.navigationController pushViewController:view animated:YES];
        }else{
            [SkToast SkToastShow:model.msg];
        }
    }];
}
-(void)appSysUserNftTokenIdVerify:(NSString*)tokenId index:(NSInteger)index{
    
    if(!self.isVerify){
        self.isVerify=YES;
        self.address=self.txtAddress.text;
        NSDictionary *dic=@{@"contractAddress":self.address,
                            @"tokenId":self.teamId
        };
        SHOW_SVP(@"Verify");
        [skNetTools skPOSTWithURL:[NSString stringWithFormat:@"%@%@",skURL,@"app/sys/user/nft/tokenId/verify"] parameters:dic cachePolicy:0 callback:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
            DISMISS_SVP(0.01);
            self.isVerify=NO;
            NSLog(@"数据=%@",responseObject);
            skNetModel *model=[skNetModel mj_objectWithKeyValues:responseObject];
            if(model.code==200){
                NSDictionary *dic=@{@"title":self.teamId,@"isTid":@YES};

                [self.arrTeamId replaceObjectAtIndex:index withObject:dic];

                [self.collectionView reloadData];
            }else{
                NSDictionary *dic=@{@"title":self.teamId,@"isTid":@NO};

                [self.arrTeamId replaceObjectAtIndex:index withObject:dic];
                [self.collectionView reloadData];
            }
        }];
    }
}
#pragma mark collectionView代理方法
//返回section个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 3;
}

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            {
                return 1;
            }
            break;
        case 1:
            {
                return 1;
            }
            break;
        case 2:
            {
                return 20;
            }
            break;
            
        default:
        {
            return 1;
        }
            break;
    }
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:KCellID forIndexPath:indexPath];
    
    for (UIView *view in cell.contentView.subviews) {
        if (view) {
            [view removeFromSuperview];
        }
    }
    switch (indexPath.section) {
        case 0:
            {
                
                UILabel *lab=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, skScreenWidth-90, 50)];
                lab.text=@"You can upload up to 20 NFTs fromthe same collection in a single batch,and you can repeat the process.";
                lab.textColor=[UIColor whiteColor];
                lab.numberOfLines=0;
                lab.font=[UIFont systemFontOfSize:13];
                [cell.contentView addSubview:lab];
                for (int i =0; i<self.arrTeamId.count; ++i) {
                    NSDictionary* dic=[self.arrTeamId objectAtIndex:i];
                    
                    Boolean ist=[[dic objectForKey:@"isTid"] boolValue];
                    NSString *title=[dic objectForKey:@"title"];
                    
                    if(title.length>0){
                        if(!ist){
                            lab.textColor=skUIColorFromRGB(0xdd7023);
                            lab.text=@"Please fill in the fields properly \nand submit again.";
                        }
                    }
                }
            }
            break;
        case 1:
            {
                UITextField *txtAddress=[[UITextField alloc] initWithFrame:CGRectMake(0, 0, skScreenWidth-90, 42)];
                txtAddress.backgroundColor=skphUIColorFromRGB(0xffffff,0.08);
                txtAddress.textAlignment=1;
                NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
                style.minimumLineHeight = 0;
                NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@"Contract Address" attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12], NSParagraphStyleAttributeName : style,NSForegroundColorAttributeName:skUIColorFromRGB(0x939598)}];
                
                txtAddress.attributedPlaceholder = attributedString;
                
                txtAddress.textColor=skUIColorFromRGB(0x939598);
                [cell.contentView addSubview:txtAddress];
                txtAddress.tag=indexPath.row;
                txtAddress.text=self.address;
                self.txtAddress=txtAddress;
            }
            break;
        case 2:
            {
                UITextField *txtAddress=[[UITextField alloc] initWithFrame:CGRectMake(0, 0, (skScreenWidth-110)/2, 42)];
                txtAddress.backgroundColor=skphUIColorFromRGB(0xffffff,0.08);
                txtAddress.textAlignment=1;
                
                NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
                style.minimumLineHeight = 0;
                NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@"Token ID" attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12], NSParagraphStyleAttributeName : style,NSForegroundColorAttributeName:skUIColorFromRGB(0x939598)}];
                
                txtAddress.attributedPlaceholder = attributedString;
                
                txtAddress.textColor=skUIColorFromRGB(0x939598);
                
                [cell.contentView addSubview:txtAddress];
                
                txtAddress.tag=indexPath.row;


                if(self.arrTeamId.count>0&&self.arrTeamId.count>=indexPath.row){
                    NSDictionary *dic=self.arrTeamId[indexPath.row];
                    
                    NSString *title=[dic objectForKey:@"title"];
                    
                    Boolean isTid=[[dic objectForKey:@"isTid"] boolValue];
                    txtAddress.text=title;
                    
                    if(isTid){
                        txtAddress.textColor=skUIColorFromRGB(0x939598);
                    }else{
                        txtAddress.textColor=skUIColorFromRGB(0xdd7023);
                    }
                }
                txtAddress.delegate=self;
                [[self rac_signalForSelector:@selector(textFieldDidEndEditing:) fromProtocol:@protocol(UITextFieldDelegate)] subscribeNext:^(RACTuple * _Nullable x) {
                    //RACTuple：元组类型

                    UITextField *field  = [x first];
                    if(field.tag==indexPath.row){
                        self.teamId=field.text;
                        [self appSysUserNftTokenIdVerify:self.teamId index:indexPath.row];
                        
                    }

                }];
            }
            break;
            
        default:
        {
            UIButton *btn=[[UIButton alloc] initWithFrame:CGRectMake(0, 20, skScreenWidth-90, 42)];
            btn.backgroundColor=skphUIColorFromRGB(0x44cd2c,0.8);
            [btn setTitle:@"Upload" forState:(UIControlStateNormal)];
            [cell.contentView addSubview:btn];
            [btn skSetBoardRadius:5 Width:0 andBorderColor:[UIColor clearColor]];
            @weakify(self)
            [[btn
              rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
                @strongify(self)
                [self appSysUserNftAdd];
                
            }];
        }
            break;
    }
    
    return cell;
}

//设置每个item的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
            {
                return CGSizeMake(skScreenWidth-90,100);
            }
            break;
        case 1:
            {
                return CGSizeMake(skScreenWidth-90,60);
            }
            break;
        case 2:
            {
                return CGSizeMake((skScreenWidth-110)/2, 42);
            }
            break;
            
        default:
        {
            return CGSizeMake(skScreenWidth-90,60);
        }
            break;
    }
}


//header的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(skScreenWidth-90, 0);
}

//设置每个item的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(1, 1, 1, 1);
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 13;
}


//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}


//通过设置SupplementaryViewOfKind 来设置头部或者底部的view，其中 ReuseIdentifier 的值必须和 注册是填写的一致，本例都为 “reusableView”
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind ==UICollectionElementKindSectionHeader){
        
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:KHedderID forIndexPath:indexPath];
        
        for (UIView *view in headerView.subviews) {
            if (view) {
                [view removeFromSuperview];
            }
        }
        
        return headerView;
    }
    
    if (kind ==UICollectionElementKindSectionFooter) {
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:KFooterID forIndexPath:indexPath];
        
        
        
        return headerView;
    }
    return nil;
}

//点击item方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
}



@end
